package com.umakr.ax.sv.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.support.json.JSONWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.sv.mapper.MessageHistoryMapper;
import com.umakr.ax.sv.model.MessageHistory;
import com.umakr.ax.utils.Mp3ConverterUtils;
//import com.umakr.ax.utils.RadioToWord;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by umakr on 2017/6/17.
 */
@Service
public class AppService extends BaseService<MessageHistoryMapper,MessageHistory> {
    private static String BaseDir = "C:\\radio\\demo-web";

    public Object upload(Integer id,String radioName,String fileSuffix,Integer audioLength,MultipartFile multipartFile){
        Integer code = 0;
        String msg = "";
        System.err.println("--------------------upload");
        long time = new Date().getTime();
        Timestamp timestamp = new Timestamp(time);
        //TODO 此处需要保存信息
        MessageHistory mh = new MessageHistory();
        if(1 == id){
            mh.setMembername("张强");
        }else{
            mh.setMembername("未知用户");
        }
        mh.setMemberid(id);
        mh.setFileshow(radioName);
        if("aac".equals(fileSuffix)){
            mh.setType("3");
            mh.setAudiolength(audioLength);
        }else if("jpg".equals(fileSuffix) || "jpeg".equals(fileSuffix) || "png".equals(fileSuffix)){
            mh.setType("2");
        }

        mh.setMessagesource(2);
        mh.setMessagestatus(1);
        mh.setFilestatus(0);
        mh.setLocalationtext("新疆大学北校区");

        //音频文件上传保存
        if(!multipartFile.isEmpty()){
            String fileAbDir = "resources" + File.separator + "upload";
            String uploadPath = BaseDir + File.separator + fileAbDir;
            File upFileDir = new File(uploadPath);
            if(!upFileDir.isDirectory()){
                upFileDir.mkdirs();
            }

            String filePath = uploadPath + File.separator + time+"."+fileSuffix;
            mh.setFilepath(fileAbDir + File.separator + time+"."+fileSuffix);
            File outPath = new File(filePath);
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outPath));
                out.write(multipartFile.getBytes());
                out.flush();
                out.close();
                if("aac".equals(fileSuffix)){
                    String destPath = uploadPath + File.separator + time;

                    System.out.println("开始转换");
                    String resultPath = Mp3ConverterUtils.convertToWav(filePath);
                    System.out.println("完成转换，开始翻译");
//                    RadioToWord mObject = new RadioToWord();
                    String result = ""; //mObject.voice2words(resultPath);
                    System.out.println("翻译结果:"+result);
                    mh.setTranslate(result);

                    Mp3ConverterUtils.convertAacToMp3(filePath,destPath+".mp3");
                    mh.setFilepath(fileAbDir + File.separator + time+".mp3");

//                    outPath.delete();
                }
                msg = "上传成功";
                mh.setCreatetime(timestamp);
                mh.setFiletime(timestamp);
                code = 1;
                update(mh);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            msg = "上传失败，录音文件时间太短";
        }

        return resultMap(code,msg);
    }

    public Object getRadioPage(Integer messagestatus){
        Page<?> page = baseMapper.getRadioPage(messagestatus);
        Integer total = page.getTotal();
        List<?> record = page.getRecords();
        JSONObject object = new JSONObject();
        object.put("total",total);
        object.put("items", JSON.parse(JSONUtils.toJSONString(record)));
        return object.toJSONString();
    }

    public Object getCurrentRadioCount(Integer messagestatus){
        Integer radioCount = baseMapper.getCurrentRadioCount(messagestatus);
        JSONObject object = new JSONObject();
        object.put("count",radioCount);
        return object.toJSONString();
    }

    public Object getMessageStatusCount(){
        return JSONUtils.toJSONString(baseMapper.getMessageStatusCount());
    }

    public Object getHistoryRadioPage(Integer filestatus){
        Page<?> page = baseMapper.getHistoryRadioPage(filestatus);
        Integer total = page.getTotal();
        List<?> record = page.getRecords();
        JSONObject object = new JSONObject();
        object.put("total",total);
        object.put("items", JSON.parse(JSONUtils.toJSONString(record)));
        return object.toJSONString();
    }

    public Object getMessages(String membername,String createtimebegin,String createtimeend,String message,String category,Integer messagestatus){
        Page<?> page = baseMapper.getMessages(membername,createtimebegin, createtimeend, message, category, messagestatus);
        Integer total = page.getTotal();
        List<?> record = page.getRecords();
        JSONObject object = new JSONObject();
        object.put("total",total);
        object.put("items", JSON.parse(JSONUtils.toJSONString(record)));
        return object.toJSONString();
    }

    public Object changeMessageStatus(Long id,Integer status){
        MessageHistory mh = queryById(id);
        mh.setMessagestatus(status);
        update(mh);
        return JSONUtils.toJSONString(Maps.newHashMap());
    }

    public Object changeFileStatus(Long id){
        MessageHistory mh = queryById(id);
        mh.setFilestatus(1);
        update(mh);
        return JSONUtils.toJSONString(Maps.newHashMap());
    }

    //批量审核
    public Object changeMultstatus(Integer[] id){
        for(int i=0; i<id.length; i++){
            MessageHistory mh = queryById((long)id[i]);
            mh.setMessagestatus(2);
            update(mh);
        }
        return JSONUtils.toJSONString(Maps.newHashMap());
    }

    //一键归档
    public Object changeMultfilestatus(Integer[] id){
        for(int i=0; i<id.length; i++){
            MessageHistory mh = queryById((long)id[i]);
            mh.setFilestatus(1);
            update(mh);
        }
        return JSONUtils.toJSONString(Maps.newHashMap());
    }

    public Object xunfeiTranslate(Long id,String file){
        MessageHistory mh = queryById(id);
        if(mh != null){
            System.out.println("开始转换");
            String destPath = Mp3ConverterUtils.convertToWav(file);

            System.out.println("完成转换，开始翻译");
//            RadioToWord mObject = new RadioToWord();
            String result = null;
//            try {
//                result = mObject.voice2words(destPath);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            System.out.println("翻译结果:"+result);
            mh.setTranslate(result);
            update(mh);
        }
        return JSONUtils.toJSONString(Maps.newHashMap());
    }

}
